//
//  AppDelegate.swift
//  weibo
//
//  Created by Fly on 2017/12/11.
//  Copyright © 2017年 Fly. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
//        sleep(2)
        
        // 额外设置
        setupAddotions()
        
        window = UIWindow()
        
        window?.backgroundColor = UIColor.white
        
        window?.rootViewController = MainViewController()
        
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

// MARK: 从服务器加载应用信息
extension AppDelegate {
    
    fileprivate func loadAppInfo() {
        
        // 1.模拟异步
        DispatchQueue.global().async {
            
            // 1.url
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            
            // 2.data
            let data = NSData(contentsOf: url!)
            
            // 3.写入磁盘
            // 3.1 取沙盒路径 数组取[0]不需要解包，如果取first/last则需要解包
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            // 3.2 保存的路径，文件名，文件格式
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            // 3.3 写入沙盒
            data?.write(toFile: jsonPath, atomically: true)
            
//            print("应用信息加载完成 \(jsonPath)")
            
        }
        
    }

}

// MARK: - 设置应用程序额外信息
extension AppDelegate {
    
    fileprivate func setupAddotions() {
        
        // 设置 SVProgressHUD 最小显示停留时间
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        // 设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        // 取得用户授权显示通知
        if #available(iOS 10.0, *) {
            
            let notificationCenter = UNUserNotificationCenter.current()
            
            notificationCenter.requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (success, error) in
                
                print("授权" + (success ? "成功" : "失败"))
                
            }
            
        }
        else
        {
            let notifySettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            
            UIApplication.shared.registerUserNotificationSettings(notifySettings)
            
        }
        
    }
    
}

